#include "widget.h"
#include "ui_widget.h"

#include <QTime>
#include "screens/CBackgroundScreen.h"
#include "screens/CMenuScreen.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    in = new CInput( this );
    sm = new CScreenManager();
    gl = new CGraphics();
    am = new CAudioManager();

    gl->setScreenManger( sm, in );
    sm->init( gl );
    sm->addSound( am );
    sm->addScreen( new CBackgroundScreen("backgroundScreen"));
    sm->addScreen( new CMenuScreen("menuScreen") );

    this->setLayout( ui->verticalLayout );
    ui->verticalLayout->addWidget( gl );

    installEventFilter( this );

    timer = new QTimer(this);
    connect( timer, SIGNAL(timeout()), this, SLOT(frame()) );
    timer->start();

}

Widget::~Widget()
{
    delete ui;
}

void Widget::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void Widget::frame()
{
    int frameTime = 16;
    timer->stop();
    static QTime time;      // laikas naudojamas nustatyti kadro laiką
    time = QTime::currentTime();

    in->handleInput();
    if ( in->wasKeyPressed(Qt::Key_F1) ) {
        if ( this->isFullScreen() )
            this->showNormal();
        else
            this->showFullScreen();
    }

    int r = sm->update( in );
    gl->updateGL();

    if ( r != -1) {
        int ms = time.msecsTo( QTime::currentTime() );  // suskaičiuojama kiek laiko užtruko kadro generaviams
        timer->start((frameTime>ms)?frameTime-ms:0);                  // jei laiko liko, galima ir pamiegoti
    } else {
        QApplication::exit();   // nutraukiamas programos vykdymas
    }
}

void Widget::keyPressEvent(QKeyEvent *e)
{
    if ( in != 0 )
        in->KeyPressedEvent( e );
}
void Widget::keyReleaseEvent(QKeyEvent *e)
{
    if ( in != 0 )
        in->KeyReleaseEvent( e );
}
void Widget::mousePressEvent(QMouseEvent* e)
{
    if ( in != 0 )
        in->mousePressEvent( e );
}
void Widget::mouseReleaseEvent(QMouseEvent *e)
{
    if ( in != 0 )
        in->mouseReleaseEvent( e );
}

// filtruoja eventus ieškodamas WindowDeactivate
bool Widget::eventFilter(QObject *o, QEvent *e)
{
    if ( e->type() == QEvent::WindowDeactivate ) {
        in->windowDeactivateEvent();
    }
    return QWidget::eventFilter( o, e );
}
